package com.example.rest.service;

import com.example.rest.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @BelongsProject: RestTemplate
 * @BelongsPackage: com.example.rest.service
 * @Author:hlzs1
 * @Description: RestTemplate 的post请求
 * @CreateTime: 2023-02-28 17:06
 * @Version: 1.0
 */
@Service
public class PostService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @description:post请求，使用forEntity
     * @author: haolizhuo
     * @date: 2023/3/1
     * @param: []
     * @return: java.lang.String
     **/
    public String postForEntity(){
        String url ="http://localhost:8090/restTemplate/hello2";
        //使用key，value的方式进行调用
        Map<String,Object> map = new HashMap<>(16);
        map.put("name","郝立琢post,map传参");
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);

        HttpHeaders headers = responseEntity.getHeaders();
        System.out.println("响应头headers===="+headers);

        String responseBody = responseEntity.getBody();
        System.out.println("响应体body===="+responseBody);

        HttpStatus statusCode = responseEntity.getStatusCode();
        System.out.println("响应状态码====" + statusCode);

        return responseEntity.getBody();
    }

    /**
     * @description:post请求，使用forEntity,传递json数据
     * @author: haolizhuo
     * @date: 2023/3/1
     * @param: []
     * @return: java.lang.String
     **/
    public String postForEntity2(){
        String url ="http://localhost:8090/restTemplate/hello2";
        //使用JSON数据进行传输，在post请求中，可以自动将一个对象转换为JSON数据进行传输
        UserModel userModel = new UserModel();
        userModel.setName("郝立琢使用JSON数据传输");

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, userModel, String.class);
        return responseEntity.getBody();
    }

    /**
     * @description:post请求，使用ForObject,传递json数据
     * @author: haolizhuo
     * @date: 2023/3/1
     * @param: []
     * @return: java.lang.String
     **/
    public String postForObject(){
        String url ="http://localhost:8090/restTemplate/hello2";
        //使用JSON数据进行传输，在post请求中，可以自动将一个对象转换为JSON数据进行传输
        UserModel userModel = new UserModel();
        userModel.setName("郝立琢调用postForObject");

        String postForObject = restTemplate.postForObject(url, userModel, String.class);
        return postForObject;
    }

}
